package apiDemo.arrayAdvance;

/**
 * 二分查找法
 */

public class Demo01 {
  public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int number = 11;

    int index = binarySearchForIndex(arr, number);
    System.out.println(index);
  }

  public static int binarySearchForIndex(int[] arr, int number) {
    int min = 0;
    int max = arr.length - 1;
    if (number < arr[min] || number > arr[max]) {
      return -1;
    }
    while (min <= max) {
      int mid = (min + max) >> 1;
      if (arr[mid] > number) {
        max = mid - 1;
      } else if (arr[mid] < number) {
        min = mid + 1;
      } else if (arr[mid] == number) {
        return mid;
      }

    }
    return -1;
  }

}
